package com.example.fragmentpriticebys;

import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;

import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toolbar;

public class MainActivity extends AppCompatActivity {

    private Button changeFragmentButton;
    private Boolean isRight;
    private Button gotoOtherActivity;
    private AnotherFragment anotherFragment;
    private RightFragment rightFragment;


    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = new Toolbar(this);
        toolbar.setLogo(R.drawable.ic_launcher_background);
        setActionBar(toolbar);
        rightFragment = new RightFragment();
        changeFragment(rightFragment,false);

        anotherFragment = new AnotherFragment();
        isRight = true;
        changeFragmentButton = findViewById(R.id.button);
        gotoOtherActivity = findViewById(R.id.go_other_activity);
        changeFragmentButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(isRight){
                    changeFragment(anotherFragment,true);
                }else{
                    changeFragment(rightFragment,false);
                }
                isRight = !isRight;
            }
        });

        gotoOtherActivity.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                FragmentManager fragmentManager = getSupportFragmentManager();
                LeftFragment leftFragment = (LeftFragment) fragmentManager.findFragmentById(R.id.left_fragment);
                Intent intent = new Intent(MainActivity.this,OtherActivity.class);
                leftFragment.startActivity(MainActivity.this,intent);
            }
        });
    }



    private void changeFragment(Fragment fragment,Boolean shouldBack){
        FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
        fragmentTransaction.replace(R.id.replace_layout,fragment);
        if(shouldBack) {
            fragmentTransaction.addToBackStack(null);
        }
        fragmentTransaction.commit();
    }
}
